import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DownloadService {

  private aLink: HTMLElement;
  private nonFilenameReg = /^[\w\W]+\//ig;

  constructor() { }

  download(url: string, filename?: string) {
    if (!this.aLink) {
      this.aLink = document.createElement('a');

    }

    this.aLink.setAttribute('href', url);
    this.aLink.setAttribute('target', '_self');
    this.aLink.setAttribute('download', filename || url.replace(this.nonFilenameReg, ''));
    this.aLink.dispatchEvent(new MouseEvent('click'));
  }

  // 下载文件流
  downloadBlob(response: BlobPart[], fileName: string) {
    if ('msSaveOrOpenBlob' in navigator) { // IE or Edge
      window.navigator.msSaveOrOpenBlob(new Blob(response), fileName);
    } else {
      if (!this.aLink) {
        this.aLink = document.createElement('a');
      }
      const blob = new Blob(response, { type: 'text/xml;charset=UTF-8' });
      const blobUrl = window.URL.createObjectURL(blob);
      this.aLink.setAttribute('download', fileName);
      this.aLink.setAttribute('href', blobUrl);
      // 兼容火狐浏览器
      this.aLink.dispatchEvent(new MouseEvent(`click`, { bubbles: true, cancelable: true, view: window }));
    }
  }
}
